package com.tangkun.environment.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.tangkun.environment.R;
import com.tangkun.environment.activity.BianJiZiLiaoActivity;
import com.tangkun.environment.entity.gongzuo.CheckBoxBean;
import com.tangkun.environment.entity.gongzuo.InspectViewReturn;
import com.tangkun.environment.utils.GsonUtil;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.MyGridView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author tangkun
 * @ClassName: XiTongTongZhiAdapter
 * @Description: 提交巡查数据子列表列表适配器
 * @date 2016-08-20 上午11:57:36
 */
public class TiJiaoXunChaShuJuItemAdapter extends BaseAdapter {

    private Context context;
    private List<InspectViewReturn.DataBean.TemplatelistBean.ItemlistBean> dataList = new ArrayList<InspectViewReturn.DataBean.TemplatelistBean.ItemlistBean>();

    public TiJiaoXunChaShuJuItemAdapter(Context context, List<InspectViewReturn.DataBean.TemplatelistBean.ItemlistBean> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    @Override
    public Object getItem(int i) {
        return dataList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_tijiaoxunchashuju_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        if (dataList != null) {
            holder.llTijiaoshujuItemTypeText.setVisibility(View.GONE);
            holder.llTijiaoshujuItemTypeRadio.setVisibility(View.GONE);
            holder.llTijiaoshujuItemTypeCheckbox.setVisibility(View.GONE);
            holder.llTijiaoshujuItemTypeDate.setVisibility(View.GONE);
            holder.llTijiaoshujuItemTypeImg.setVisibility(View.GONE);
            //类型
            switch (dataList.get(position).type) {
                case "text"://文本输入框
                    holder.llTijiaoshujuItemTypeText.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.etTijiaoshujuItemTypeText.setHint(dataList.get(position).key);
                    } else {
                        holder.etTijiaoshujuItemTypeText.setHint("");
                    }
                    //value
                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        holder.etTijiaoshujuItemTypeText.setText(dataList.get(position).value);
                    } else {
                        holder.etTijiaoshujuItemTypeText.setText("");
                    }
                    //文本输入框监听
                    holder.etTijiaoshujuItemTypeText.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                        }

                        @Override
                        public void afterTextChanged(Editable editable) {
                            String ids = dataList.get(position).ids;
                            String value = holder.etTijiaoshujuItemTypeText.getText().toString().trim();
                            LogUtils.e("Edittext：" + value + " value：" + dataList.get(position).value);
                            if (dataList.get(position).value == null || !value.equals(dataList.get(position).value)) {
                                dataList.get(position).value = value;
                                myClickListener.onMyClick("text", ids, value);
                            }
                        }
                    });
                    break;
                case "radio"://单选框
                    holder.llTijiaoshujuItemTypeRadio.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.tvTijiaoshujuItemTypeRadio.setText(dataList.get(position).key);
                    } else {
                        holder.tvTijiaoshujuItemTypeRadio.setText("");
                    }

                    //增加监听事件，文字过多点击用对话框展示
                    holder.tvTijiaoshujuItemTypeRadio.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String ids = dataList.get(position).ids;
                            String key = dataList.get(position).key;
                            myClickListener.onMyClick("radioKey", ids, key);
                        }
                    });

                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        String jsonString = dataList.get(position).value;
                        jsonString = jsonString.replaceAll("\\\\", "");
                        List<CheckBoxBean> checkBoxBeanList = GsonUtil.GsonToList(jsonString, CheckBoxBean.class);
                        int selectedIndex = 0;
                        for (int i = 0; i < checkBoxBeanList.size(); i++) {
                            if (checkBoxBeanList.get(i).value.equals("1")) {
                                //选中项
                                selectedIndex = i;
                            }
                        }
                        //清除所有控件
                        holder.rgTijiaoshujuItemTypeRadio.removeAllViews();
                        for (int j = 0; j < checkBoxBeanList.size(); j++) {
                            RadioButton button = new RadioButton(context);
                            if (j == selectedIndex) {
                                button.setChecked(true);
                            } else {
                                button.setChecked(false);
                            }
                            setRadioBtnAttribute(button, checkBoxBeanList.get(j).key, j, dataList.get(position).ids, checkBoxBeanList);
                            holder.rgTijiaoshujuItemTypeRadio.addView(button);
                            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) button
                                    .getLayoutParams();
                            //设置间距
                            layoutParams.setMargins(0, 0, Utils.dp2px(context, 10), 0);//4个参数按顺序分别是左上右下
                            button.setLayoutParams(layoutParams);
                        }
                    } else {
                        //清除所有控件
                        holder.rgTijiaoshujuItemTypeRadio.removeAllViews();
                    }
                    break;
                case "checkbox"://复选框
                    holder.llTijiaoshujuItemTypeCheckbox.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.tvTijiaoshujuItemTypeCheckboxName.setText(dataList.get(position).key);
                    } else {
                        holder.tvTijiaoshujuItemTypeCheckboxName.setText("");
                    }
                    //value
                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        String jsonString = dataList.get(position).value;
                        jsonString = jsonString.replaceAll("\\\\", "");
                        List<CheckBoxBean> checkBoxBeanList = GsonUtil.GsonToList(jsonString, CheckBoxBean.class);
                        String selectedText = "";
                        for (CheckBoxBean bean : checkBoxBeanList) {
                            if (bean.value.equals("1")) {
                                selectedText = selectedText + " " + bean.key;
                            }
                        }
                        holder.tvTijiaoshujuItemTypeCheckboxValue.setText(selectedText + "");
                    } else {
                        holder.tvTijiaoshujuItemTypeCheckboxValue.setText("");
                    }
                    //点击事件
                    holder.llTijiaoshujuItemTypeCheckbox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String ids = dataList.get(position).ids;
                            String value = dataList.get(position).value;
                            myClickListener.onMyClick("checkbox", ids, value);
                        }
                    });
                    break;
                case "date"://选择日期
                    holder.llTijiaoshujuItemTypeDate.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.tvTijiaoshujuItemTypeDateName.setText(dataList.get(position).key);
                    } else {
                        holder.tvTijiaoshujuItemTypeDateName.setText("");
                    }
                    //value
                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        holder.tvTijiaoshujuItemTypeDateValue.setText(Utils.getDateYearMonthDay(dataList.get(position).value));
                    } else {
                        holder.tvTijiaoshujuItemTypeDateValue.setText("");
                    }
                    //点击事件
                    holder.tvTijiaoshujuItemTypeDateValue.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String ids = dataList.get(position).ids;
                            String value = dataList.get(position).value;
                            myClickListener.onMyClick("date", ids, value);
                        }
                    });
                    break;
                case "img"://上传图片
                    holder.llTijiaoshujuItemTypeImg.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.tvTijiaoshujuItemTypeImg.setText(dataList.get(position).key);
                    } else {
                        holder.tvTijiaoshujuItemTypeImg.setText("");
                    }
                    //value
                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        List<String> urlList = Arrays.asList(dataList.get(position).value.split(","));
                        ImageUrlNoAddAdapter adapter = new ImageUrlNoAddAdapter((Activity) context, R.layout.weibo_pic_list);
                        adapter.setIdDongtaiImg(dataList.get(position).ids);//设置动态图片(GridView)ID
                        adapter.setCanDelete(true);
                        adapter.setREQUEST_CODE(BianJiZiLiaoActivity.REQUEST_CODE_BASICLIST_SELECTED_IMG);
                        adapter.getUrlList();// initialize
                        adapter.setUrlList(urlList);//赋值
                        Utils.setGridViewHeightBasedOnChildren(holder.mygridview, 7);
                        holder.mygridview.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                        holder.mygridview.setVisibility(View.VISIBLE);
                    } else {
                        holder.mygridview.setVisibility(View.GONE);
                    }
                    //点击事件
                    holder.ivTijiaoshujuItemTypeImg.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            String ids = dataList.get(position).ids;
                            String value = dataList.get(position).value;
                            String key = dataList.get(position).key;
                            if (!TextUtils.isEmpty(key) && key.equals("受检单位签章")) {
                                myClickListener.onMyClick("imgSign", ids, value);
                            } else {
                                myClickListener.onMyClick("img", ids, value);
                            }
                        }
                    });
                    break;
                case "file"://文件 暂时和复选框一样显示
                    holder.llTijiaoshujuItemTypeCheckbox.setVisibility(View.VISIBLE);
                    //key
                    if (!TextUtils.isEmpty(dataList.get(position).key)) {
                        holder.tvTijiaoshujuItemTypeCheckboxName.setText(dataList.get(position).key);
                    } else {
                        holder.tvTijiaoshujuItemTypeCheckboxName.setText("");
                    }
                    //value
                    if (!TextUtils.isEmpty(dataList.get(position).value)) {
                        holder.tvTijiaoshujuItemTypeCheckboxValue.setText(dataList.get(position).value + "");
                    } else {
                        holder.tvTijiaoshujuItemTypeCheckboxValue.setText("");
                    }
                    break;
            }

            /*****当选择无时，下一行内容隐藏。 parentid为空肯定显示这一项*****/
            //parentid为空肯定显示这一项
            if (TextUtils.isEmpty(dataList.get(position).parentid)) {
                //ignore
            } else {
                //parentid非空 判断这个数据源里面有没有ids和这个parentid相等的，如果有相等的，并且他的value里面的childids和ids相等，并且其value为1，就显示当前item，否则隐藏该item
                for (InspectViewReturn.DataBean.TemplatelistBean.ItemlistBean bean : dataList) {
                    //判断这个数据源里面有没有ids和这个parentid相等的，如果有相等的
                    if (bean.ids.equals(dataList.get(position).parentid)) {
                        if (!TextUtils.isEmpty(bean.value)) {
                            //并且他的values里面的childids和parentid相等，并且其values为1，就显示当前item，否则隐藏该item
                            String jsonString = bean.value;
                            jsonString = jsonString.replaceAll("\\\\", "");
                            List<CheckBoxBean> checkBoxBeanList = GsonUtil.GsonToList(jsonString, CheckBoxBean.class);
                            //是否选中了有
                            boolean isYesChecked = false;
                            for (int i = 0; i < checkBoxBeanList.size(); i++) {
                                //可能有多个ID以逗号隔开;
                                String childidsArray[] = checkBoxBeanList.get(i).childids.split(",");
                                List<String> childidsList = Arrays.asList(childidsArray);
                                //集合里边包含了这个ID的都隐藏
                                if (childidsList.contains(dataList.get(position).ids) && checkBoxBeanList.get(i).value.equals("1")) {
//                        if (checkBoxBeanList.get(i).childids.equals(dataList.get(position).ids) && checkBoxBeanList.get(i).value.equals("1")) {
                                    //选中了有 显示
                                    isYesChecked = true;
                                }
                            }
                            //当选择无时，下一行内容隐藏
                            if (!isYesChecked) {
                                holder.llTijiaoshujuItemTypeText.setVisibility(View.GONE);
                                holder.llTijiaoshujuItemTypeRadio.setVisibility(View.GONE);
                                holder.llTijiaoshujuItemTypeCheckbox.setVisibility(View.GONE);
                                holder.llTijiaoshujuItemTypeDate.setVisibility(View.GONE);
                                holder.llTijiaoshujuItemTypeImg.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }
        }
        return convertView;

    }

    /**
     * 设置radioButton属性
     *
     * @param radioButton      radioButton按钮
     * @param btnContent       radioButton上文案
     * @param index            radioButton的索引
     * @param ids              该item的ids
     * @param checkBoxBeanList 该item的value转换的集合
     */
    private void setRadioBtnAttribute(final RadioButton radioButton, String btnContent, final int index, final String ids, final List<CheckBoxBean> checkBoxBeanList) {
        if (null == radioButton) {
            return;
        }
        radioButton.setBackgroundResource(R.drawable.radiobutton_background_green_selector);
        radioButton.setTextColor(context.getResources().getColorStateList(R.color.radiobutton_green_color));
        radioButton.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
        //radioButton.setTextSize( ( textSize > 16 )?textSize:24 );
        radioButton.setId(index);
        radioButton.setText(btnContent);
        //radioButton.setPadding(2, 0, 2, 0);
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //都置为未选中
                for (CheckBoxBean bean : checkBoxBeanList) {
                    bean.value = "0";
                }
                //将该选中索引button的值为选中
                checkBoxBeanList.get(index).value = "1";
                //ID对应的value json字符串
                String value = GsonUtil.GsonToString(checkBoxBeanList);
                LogUtils.e("ids：" + ids + "   value：" + value);
                myClickListener.onMyClick("radio", ids, value);
            }
        });
        LinearLayout.LayoutParams rlp;
        //文字过多处理
        if (btnContent.length() > 3) {
            radioButton.setPadding(Utils.dp2px(context, 5), 0, Utils.dp2px(context, 5), 0);
            rlp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, Utils.dp2px(context, 25));
        } else {
            radioButton.setPadding(0, 0, 0, 0);
            rlp = new LinearLayout.LayoutParams(Utils.dp2px(context, 50), Utils.dp2px(context, 25));
        }
        radioButton.setLayoutParams(rlp);
    }

    /**
     * 自定义接口回调
     */
    private TiJiaoXunChaShuJuItemAdapter.MyClickListener myClickListener;

    public void setMyClickListener(TiJiaoXunChaShuJuItemAdapter.MyClickListener myClickListener) {
        this.myClickListener = myClickListener;
    }

    public interface MyClickListener {
        void onMyClick(String type, String ids, String value);
    }

    static class ViewHolder {
        @BindView(R.id.et_tijiaoshuju_item_type_text)
        EditText etTijiaoshujuItemTypeText;
        @BindView(R.id.ll_tijiaoshuju_item_type_text)
        LinearLayout llTijiaoshujuItemTypeText;
        @BindView(R.id.tv_tijiaoshuju_item_type_radio)
        TextView tvTijiaoshujuItemTypeRadio;
        @BindView(R.id.rb_tijiaoshuju_item_type_radio_yes)
        RadioButton rbTijiaoshujuItemTypeRadioYes;
        @BindView(R.id.rb_tijiaoshuju_item_type_radio_no)
        RadioButton rbTijiaoshujuItemTypeRadioNo;
        @BindView(R.id.rg_tijiaoshuju_item_type_radio)
        RadioGroup rgTijiaoshujuItemTypeRadio;
        @BindView(R.id.ll_tijiaoshuju_item_type_radio)
        LinearLayout llTijiaoshujuItemTypeRadio;
        @BindView(R.id.tv_tijiaoshuju_item_type_checkbox_name)
        TextView tvTijiaoshujuItemTypeCheckboxName;
        @BindView(R.id.tv_tijiaoshuju_item_type_checkbox_value)
        TextView tvTijiaoshujuItemTypeCheckboxValue;
        @BindView(R.id.ll_tijiaoshuju_item_type_checkbox)
        LinearLayout llTijiaoshujuItemTypeCheckbox;
        @BindView(R.id.tv_tijiaoshuju_item_type_date_name)
        TextView tvTijiaoshujuItemTypeDateName;
        @BindView(R.id.tv_tijiaoshuju_item_type_date_value)
        TextView tvTijiaoshujuItemTypeDateValue;
        @BindView(R.id.ll_tijiaoshuju_item_type_date)
        LinearLayout llTijiaoshujuItemTypeDate;
        @BindView(R.id.tv_tijiaoshuju_item_type_img)
        TextView tvTijiaoshujuItemTypeImg;
        @BindView(R.id.iv_tijiaoshuju_item_type_img)
        ImageView ivTijiaoshujuItemTypeImg;
        @BindView(R.id.mygridview)
        MyGridView mygridview;
        @BindView(R.id.ll_tijiaoshuju_item_type_img)
        LinearLayout llTijiaoshujuItemTypeImg;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
